package com.xjtu.chapter09;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

/**
 * @author yjq
 * @version 1.0
 * @date 2021/9/4 22:25
 */

//Product实现Comparable比较器，本身支持排序
class ProductMe implements Comparable<ProductMe>{
   int id;
   String name;

    public ProductMe(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return name+"-"+id;
    }

    @Override
    public int compareTo(ProductMe productMe) {
        return name.compareTo(productMe.name);
    }
}

//为ProductMe创建一个升序比较器，根据id升序排序
class AscComparator implements Comparator<ProductMe>{

    @Override
    public int compare(ProductMe productMe, ProductMe t1) {
        return productMe.getId()-t1.getId();
    }
}
//为ProductMe创建一个降序比较器，根据id升序排序
class DescComparator implements Comparator<ProductMe>{

    @Override
    public int compare(ProductMe productMe, ProductMe t1) {
        return t1.getId()-productMe.getId();
    }
}
public class CompareTest {
    public static void main(String[] args) {
        ArrayList<ProductMe>list = new ArrayList<>();
        list.add(new ProductMe(12,"a"));
        list.add(new ProductMe(10,"c"));
        list.add(new ProductMe(22,"d"));
        list.add(new ProductMe(11,"b"));
        System.out.printf("original sort,list: %s\n",list);

        //对list进行排序，按照ProductMe实现的CompareTo()进行排序
        Collections.sort(list);
        System.out.printf("product name sorted list:%s\n",list);

        //通过比较器AscComparator进行排序
        Collections.sort(list,new AscComparator());
        System.out.printf("asc id sorted,list:%s\n",list);

        //通过比较器DescComparator进行排序
        Collections.sort(list,new DescComparator());
        System.out.printf("desc id sorted,list:%s\n",list);
    }
}
